package com.atguigu.spring5.testdemo;

import com.alibaba.druid.pool.DruidDataSource;
import com.atguigu.spring5.autowire.Emp;
import com.atguigu.spring5.bean.Orders;
import com.atguigu.spring5.collectiontype.Book;
import com.atguigu.spring5.collectiontype.Course;
import com.atguigu.spring5.collectiontype.Stu;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring5Demo1 {

    //注入集合类型
    @Test
    public void testCollection1() {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean1.xml");
        Stu stu = context.getBean("stu", Stu.class);
        stu.test();
    }

    //提取list集合类型属性注入使用
    //单实例，scope="prototype" 创建多实例对象。
    @Test
    public void testCollection2() {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean2.xml");
        Book book1 = context.getBean("book", Book.class);
        Book book2 = context.getBean("book", Book.class);
       // book.test();
        System.out.println(book1);
        System.out.println(book2);
    }

    //Factory Bean, 此Bean可以创建其他类型的Bean
    @Test
    public void testFactoryBean() {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean3.xml");
        Course course = context.getBean("myBean", Course.class);
        System.out.println(course);
    }

    //Bean的生命周期（共7步），需要在xml配置bean的属性，init-method="initMethod" destroy-method="destroyMethod"
    //xml中配置后置处理器。bean创建前后会交给后置处理器处理。
    @Test
    public void testBeanLife() {
        ClassPathXmlApplicationContext context =
                new ClassPathXmlApplicationContext("bean4.xml");
        Orders orders = context.getBean("orders", Orders.class);
        System.out.println("第四步 获取创建bean实例对象");
        System.out.println(orders);

        //手动让bean实例销毁
        context.close();
    }

    //自动装配，需要在xml配置bean的属性 autowire="byType"
    @Test
    public void testAutoWire() {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean5.xml");
        Emp emp = context.getBean("emp", Emp.class);
        System.out.println(emp);
    }

    //引入配置文件，类的属性注入，从配置文件读取
    @Test
    public void testDIFromProperties() {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean6.xml");
        DruidDataSource ds = context.getBean("dataSource", DruidDataSource.class);
        System.out.println(ds);
    }

}
